package com.xzz.listnode;

/**
 * @author: hhz
 * @create: 2021-12-15 14:40
 **/
public class ListPartition {
    public static void main(String[] args) {
        ListNode head = new ListNode(1,new ListNode(4,new ListNode(3,new ListNode(2,new ListNode(5,new ListNode(2))))));
        ListNode node = head;
        while (null != node){
            System.out.print(node.val);
            if(node.next!=null){
                System.out.print(",");
            }
            node = node.next;
        }
        System.out.println();
        ListNode partition = partition(head, 3);
        while (null != partition){
            System.out.print(partition.val);
            if(partition.next!=null){
                System.out.print(",");
            }
            partition = partition.next;
        }
    }
    public static ListNode partition(ListNode head, int x) {
        ListNode leftNode = new ListNode(0);
        ListNode leftHead = leftNode;
        ListNode rightNode = new ListNode(0);
        ListNode rightHead = rightNode;
        while (null != head){
            if(head.val<x){
                leftNode.next = head;
                leftNode = leftNode.next;
            }else {
                rightNode.next = head;
                rightNode = rightNode.next;
            }
            head = head.next;
        }
        //避免成环
        rightNode.next = null;
        leftNode.next = rightHead.next;
        return leftHead.next;
    }

   static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
